$(function(){
	var no = 1;
	var tSearch = null;
	var sends = null;
	var caogao = 0;
	var caogaoid = 0
	// 自定义错误处理
	var error = new Error();
	error.newHandle({
		errorCallback: function (fn) {
			if ($.type(fn) === "function") fn();
		}
	});
	// 接口
	var oDataSource = {
		getAnnounceType: function (oData) {
			return $.ajax({
				url: Site("getAnnounceType"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		/**
		 * 删除记名名单
		 * @param oData:{id}
		 * @return {Object} Deferred对象
		 */
		deleteAnnouncementByUser: function (oData) {
			return $.ajax({
				url: Site("deleteAnnouncementByUser"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		/*
		 * 发布给哪些人员的加载
		 * */
		getAllNodePlat: function (oData) {
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("getAllNodePlat"),
				dataType:"json",
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		//发布公告接口
		addAnnouncement:function(oData){
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("addAnnouncement"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		//未读信息接口
		totalUnreadOnUser:function (oData){
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("totalUnreadOnUser"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		insertAnnouncementType:function(oData){
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("insertAnnouncementType"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		//查看草稿
		viewDraft:function(oData){
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("viewDraft"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
		//发送或保存草稿
		releaseDraft:function(oData){
			//console.log("oDate------",oData)
			return $.ajax({
				url: Site("releaseDraft"),
				method: "get",
				data: {data: JSON.stringify(oData)}
			});
		},
	deleteAttachment:function(oData){
		//console.log("oDate------",oData)
		return $.ajax({
			url: Site("deleteAttachment"),
			method: "get",
			data: {data: JSON.stringify(oData)}
		});
	},
	};
	var selector = {
		sendNotice:"#sendNotice",
		table:"#table",
		summernote:".summernote",
		public:"#public",
		unread:"#unread",
		draft:"#draft",
		noType:"#noType",
		sendP:"#sendP",
		start:"#start",
		end:"#end",
		titleLike:"#titleLike",
		nameLike:"#nameLike",
		search:"#search",
		searcher:"#searcher",
		toolbar:"#toolbar",
		formEditDevice:"#formEditDevice",
		errorMsg:"#errorMsg",
		timeSearch:"#timeSearch",
		aboutme:"#aboutme",
		title:"#title",
		autoType:"#autoType",
		showModal:"#showModal",
		saveNotice:"#saveNotice",
		content:"#content",
		modal:"#modal",
		unR:"#unR",
		dropzone:".dropzone",
		jstree:"#jstree",
		fileName:"#fileName",
		demo_drop:".demo_drop",
		Afilename:"#Afilename",
		Asize:"#Asize",
		remove:"#remove",
		files:"#files"
	}
	//判断是哪个平台
	if(Account.level === 1){
		$(selector.showModal).css("display","none");
		$(selector.public).css("display","none");
	}
	//表单验证
	$(selector.formEditDevice).validate({
		rules: {
			title: "required",
			content: "required",
			autoType:{
				"autoType":true
			}
		},
		messages: {
			title: {required: '<span class="fa fa-times-circle"></span> 主题不能为空'},
			content: {required: '<span class="fa fa-times-circle"></span> 内容不能为空'},
			autoType:{autoType:'<span class="fa fa-times-circle"></s$pan> 类型需是20个以内的汉字'}
		},
		errorElement: "span",
		errorClass: "text-danger",
		errorPlacement: function ($error, $control) {
			$(selector.errorMsg).html($error);
		}
	});
	$.validator.addMethod("autoType", function(value, element, param) {
		var chinese = /^[\u4E00-\u9FA5]{0,20}$/;
		if(!chinese.test(value))
			return false;
		return true
	});
	$(document).on('click',function(e){
		oDataSource.getAllNodePlat({account:Account.user.account}).then(function(data){
			$(selector.jstree).jstree({
				'plugins' : [ 'wholerow', 'checkbox'],
				'types':{
					'default':{
						'icon':"glyphicon glyphicon-leaf"
					}
				},
				'core':{
					'data':data,
				},
			})
		});
		$(selector.jstree).hide();
		e.stopPropagation();
	})
	$(selector.sendP).on('click',function(e){
		$(selector.jstree).toggle();
		//console.log($(selector.jstree).css("display"))
		e.stopPropagation();
	})
	$(selector.jstree).bind("click.jstree", function (e) {
		e.stopPropagation();
	});
	//选择时间
	$(selector.timeSearch).on('change',function(e){
		tSearch = this.value;
		$(selector.table).bootstrapTable("refresh");
	});
	//类型加载
	oDataSource.getAnnounceType().then(function(data){
		error.listen(data.code).not(function(){
			$(selector.noType).empty();
			$(data.announcementTypelist).each(function (n) {
				$("<option/>").html(this).val(this).appendTo(selector.noType);
			});
		})
	});
	//删除文件
	function delfile(a){
		console.trace();
		$(this).css("display","none")
		//console.log("delfile:",this)
		oDataSource.deleteAttachment({id:a}).then(function(data){
			error.listen(data.code).not(function () {
				//console.log("删除成功")
			})
		})
	}
	//未读信息加载
	oDataSource.totalUnreadOnUser({account:Account.user.account}).then(function(data){
		error.listen(data.code).not(function(){
			if(data.total){
				$(selector.unR).css({
					"display":"inline-block",
					"background-color":"red",
					"width":"16px",
					"height":"16px",
					"border-radius":"8px",
					"position":"absolute",
					"top":"-5px",
					"right":"0",
					"font-size":"12px",
					"color":"#fff"
				}).html(data.total);
			}
		})
	});
	function del(row){
		swal({
			title: "确定删除吗？",
			text: "你将无法恢复该名单！",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "确定删除！",
			closeOnConfirm: false
		},function(){
			oDataSource.deleteAnnouncementByUser(row).then(function(data){
				swal({
					title:"删除！",
					type:"success"
				},function(){
					$(selector.table).bootstrapTable('refresh');
				});
			})
		});
	}
	//富文本框
	$(selector.summernote).summernote({
		height: 200,
		tabsize: 2,
		lang: 'zh-CN',
		toolbar: [
			// [groupName, [list of button]]
			['style', ['bold', 'italic', 'underline', 'clear']],
			['font', ['strikethrough', 'superscript', 'subscript']],
			['fontsize', ['fontsize']],
			['color', ['color']],
			['para', ['ul', 'ol', 'paragraph']],
			['height', ['height']]
		]
	});

	$(selector.modal).on('hidden.bs.modal', function() {
		$("input").val("");
		$("input").removeClass("text-danger");
		$(selector.jstree).data('jstree', false).empty();
		$(selector.summernote).summernote('code','')
		$(selector.errorMsg).html("");
		$(selector.dropzone).html("")
	});
	//类型名称与自定义类型
	$(selector.noType).change(function(){
		$(selector.noType).removeAttr("disabled");
		$(selector.autoType).val("");
	});

	//发布与保存
	$([selector.sendNotice,selector.saveNotice].join(",")).click(function(){
		if (!$(selector.formEditDevice).validate().form()) {
			return;
		}
		var auToype = $.trim($(selector.autoType).val());
		if(auToype != ""){
			var insert = {
				account:Number(Account.user.account),
			}
			insert.type = auToype;
		}
		var announce = {
			announcement:{
				name:Account.user.name,
				post:this.value,
				attachmentId:fileArr
			},
			account:Account.user.account,
			idList:[]
		}
		console.log(JSON.stringify(announce.announcement.attachmentId))
		if($(selector.jstree).jstree(true))
			announce.idList = $(selector.jstree).jstree(true).get_selected()
		var title = $.trim($(selector.title).val());
		if ($.trim(title) !== "") announce.announcement.title = title || null;

		var content = $(selector.summernote).summernote('code');
		if ($.trim(content) !== "") announce.announcement.content = content || null;

		var type = $.trim($(selector.noType).val());
		if(auToype === ""){
			if ($.trim(type) !== "") announce.announcement.type = type || null;
		}else announce.announcement.type = auToype;

		//console.log(announce)
		//console.log("this.value---",this.value);
		if(this.value == 1)
			return sendswal(announce,insert,auToype);
		if(caogao === 1){
			announce.announcement.id = caogaoid;
			console.log("announce:",announce)

			oDataSource.releaseDraft (announce).then(function(data){
				//error.listen(data.code).not(function()
				error.listen(data.code).not(function(){
					caogao = 0
					//console.log("已成功保存到后端",data)
					swal("已保存！","","success");
					$(selector.modal).modal("toggle");
					if(auToype !== ""){
						oDataSource.insertAnnouncementType(insert).then(function(data){
							error.listen(data.code).not(function(){
								//console.log("===添加类型===",data)
							})
						})
					}
					$(selector.table).bootstrapTable("refresh");
				})
			})
		}else{
			console.log("bannounce",announce)
			oDataSource.addAnnouncement (announce).then(function(data){
				error.listen(data.code).not(function(){
					swal("已保存！","","success");
					$(selector.modal).modal("toggle");
					if(auToype !== ""){
						oDataSource.insertAnnouncementType(insert).then(function(data){
							error.listen(data.code).not(function(){
								//console.log("===添加类型===",data)
							})
						})
					}
					$(selector.table).bootstrapTable("refresh");
				})
			})
		}

	});
	//查询与我相关
	$([selector.aboutme,selector.public,selector.unread,selector.draft].join(",")).click(function(){
		$(this).addClass("active").siblings().removeClass("active");
		no = this.value
		$(selector.table).bootstrapTable("refresh");
	});

	$(selector.table).bootstrapTable({
		url:Site("findAnnouncement"),
		//url:"data/device.json",
		contentType: "application/x-www-form-urlencoded",
		sidePagination: "server",
		striped: true,
		pagination: true,
		pageSize: 10,
		pageList: [10, 20, 30, 50, 100],
		toolbar: "#toolbar",
		search: false,
		searchOnEnterKey: false,
		selectItemName: "btSelectItem",
		queryParams: queryParams,
		responseHandler: responseHandler,
		columns: [{
				field:"id",align:"center",title: "id",visible:false
			},{
			field: "read",align:"center",title: "状态",
			formatter: function (value) {
				if(value == 1) {
					return "<span class='glyphicon glyphicon-envelope' style='font-size: 20px'></span>";
				} else if(value == 0) {
					return "<span class='glyphicon glyphicon-envelope' style='font-size: 20px;position: relative' ><span class='point'> . </span></span>";
				} else {
					return "-";
				}
			}
		},{
			field:"title",align:"center",title:"主题"
		},{
			field: "name",align:"center",title: "发件人"
		},{
			field: "type",align:"center",title: "类型"
		},{
			field:"releaseTime",align:"center",title:"时间↓",
			formatter: function (value) {
				if (value != null) {
					return new Date(value).Format("yyyy-MM-dd hh:mm:ss");
				}
			}

		},{
			field:"operation",
			title:"操作",
			align:"center",
			width: "150px",
			formatter: function (value, row) {
				if(no == 4)
					return '<button class="btn btn-info btn-outline edit">编辑</button>&nbsp;&nbsp;<button class="btn btn-info btn-outline del">删除</button>'
				return '<button class="btn btn-info btn-outline look">详情</button>&nbsp;&nbsp;<button class="btn btn-info btn-outline del">删除</button>'

			},
			events: {
				"click .look":function(ev, value, row,index){
					location = 'viewNotice.html?id='+row.id;
				},
				"click .del": function (ev, value, row,index) {
					var delannounce = {
						noticeId:row.id,
						account:Account.user.account
					}
					del(delannounce)
				},
				"click .edit": function (ev,value,row,index) {
					var edit = {
						noticeId:row.id,
						account:Account.user.account
					}
					oDataSource.getAnnounceType().then(function(data){
						error.listen(data.code).not(function(){
							$(selector.noType).empty();
							$(data.announcementTypelist).each(function (n) {
								$("<option/>").html(this).val(this).appendTo(selector.noType);
							});
						})
					});
					oDataSource.viewDraft(edit).then(function(data){
						$(selector.modal).modal("toggle");
						console.log("viewDraft-data:",data)
						error.listen(data.code).not(function(){
							caogao = 1;
							caogaoid = data.announcement.id
							var announcement = data.announcement;
							var nodeList = data.nodeList;
							for(var i=0; i<nodeList.length; i++)
								$(selector.jstree).jstree('select_node', nodeList[i].nodeId);
							$(selector.title).val(row.title); //公告标题
							$(selector.summernote).summernote('code',row.content);//内容
							$(selector.noType).val(row.type)//类型
							console.log("草稿--------",data)
							if(data.attachmentMap){
								$(".dz-default.dz-message").css("display","none");
								for(var i=0; i<data.attachmentMap.length; i++){
									//console.log("===草稿=====",data.attachmentMap[i].fileName)
									$(selector.files).append("<tr><td>"+data.attachmentMap[i].fileName+"</td>"
										+"<td>"+data.attachmentMap[i].fileSize+"</td>"
										+"<td><a href='#' id='"+data.attachmentMap[i].id+ "'>移除文件</a></td></tr>")
									fileArr.push(data.attachmentMap[i].id);
								}
							}
						})
					})
				},
			}
		}]
	});
	$(selector.files).on('click','a',function(){
		console.log(this)
		$(this.parentNode.parentNode).hide()
		delfile(this.id)
	})
	function queryParams(params) {
		sends = {
			page: parseInt(params.offset / params.limit) + 1,  //当前页
			numberOfPage: params.limit    //每页记录数
		};
		//根据account筛选
		var account = $.trim(Account.user.account);
		if($.trim(account) !== "") sends.account = Number(account) || null;

		if($.trim(Account.level) !== "") sends.state = Number(no);

		sends.timeState = Number(tSearch);

		var nameLike= $.trim($(selector.nameLike).val());
		 sends.nameLike =(nameLike);  //发布者

		var titleLike= $.trim($(selector.titleLike).val());
		sends.titleLike =(titleLike);

		return {data: JSON.stringify(sends)};
	}
	function responseHandler(res) {
		if(res && $.type(res.announcemenTextMapList) === "array" && res.announcemenTextMapList.length > 0) {
			return {rows: res.announcemenTextMapList, total: res.total};
		}
		return {rows: [], total: 0};
	}
	//发布提醒
	function sendswal(announce,insert,autoType) {
		swal({
				title: "确定发布吗？",
				type:"warning",
				showCancelButton: true,
				confirmButtonColor: "#DD6B55",
				confirmButtonText: "确定发布！",
				cancelButtonText: "取消发布！",
				closeOnConfirm: false,
				closeOnCancel: false
			},
			function(isConfirm){
				if (isConfirm) {
					if(caogao == 1){
						announce.announcement.id = caogaoid
						oDataSource.releaseDraft(announce).then(function(data){
							swal("成功发布！","","success");
							$(selector.modal).modal("toggle");
							$(selector.table).bootstrapTable("refresh");
							if(autoType !== ""){
								oDataSource.insertAnnouncementType(insert).then(function(data){
									error.listen(data.code).not(function(){
										//console.log("===添加类型===",data)
									})
								})
							}
						})
						caogao = 0;
					}else{
						oDataSource.addAnnouncement(announce).then(function(data){
							swal("成功发布！","","success");
							$(selector.modal).modal("toggle");
							$(selector.table).bootstrapTable("refresh");
							if(autoType !== ""){
								oDataSource.insertAnnouncementType(insert).then(function(data){
									error.listen(data.code).not(function(){
										//console.log("===添加类型===",data)
									})
								})
							}
						})
					}
				} else {
					swal("取消发布！","","error");
				}
			});
	}

	//titlelike 改变
	$([selector.titleLike,selector.nameLike].join(",")).bind('keyup change',function(){
		$(selector.table).bootstrapTable("refresh");
	});

	//上传文件
	Dropzone.autoDiscover = false;
	var fileArr = new Array();
	$(selector.dropzone).dropzone({
		url:Site("uploadAttachment"),
		method:"post",
		paramName:"file",   //后端同学的字段
		autoProcessQueue:true,//自动上传
		maxFilesize:1024, // MB
		uploadMultiple:false,
		parallelUploads:10,
		acceptedFiles:".doc,.wps,.xls,.pdf,.jpg",
		dictInvalidFileType:"支持的文件类型是.doc,.wps,.xls,.pdf,.jpg",
		addRemoveLinks:true,  //删除按钮
		dictRemoveFile:"移除文件",
		dictUploadCanceled:"取消",
		dictDefaultMessage:
			"<span class='bigger-150 bolder'><i class='icon-caret-right red'></i>拖动文件</span>上传\
            <span class='smaller-80 gre'>(或者点击上传)</span> <br /> \
            <i class='upload-icon icon-cloud-upload blue icon-3x'></i>",
		dictResponseError:"文件上传失败!",
		dictFileTooBig:"文件过大,上传失败!",
		init:function(){
			this.on("addedfile",function(file,data) {
				console.log("file:",file)
			})
			this.on("success",function(file,data){
				console.log("success:",data)
				error.listen(data.code).not(function(){
					fileArr.push(data.id);
					console.log("fileArr[]:",fileArr)
				})
			});
			this.on("error", function () {
				//console.log("++",arguments)
			});
			this.on("removedfile",function(file){
				//解决点击时重复发送请求
				//console.log(file)
				$(".dz-remove").each(function(index) {
					if(!$(".dz-remove:eq(" + index + ")").attr("id")) {
						$(".dz-remove:eq(" + index + ")").attr("id",fileArr[index]);
					}
					delfile(fileArr[index])
				})
			})
		},
	});
})



